package com.ruoyi.common.utils;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;

/**
 * 获取地址类
 * 
 * @author ruoyi
 */
public class AddressUtils{
	
	//升级收益
    public static final int INCOME_SJ = 0;
    //还款收益
    public static final int INCOME_YK = 1;
    //快捷收益
    public static final int INCOME_WK = 2;
    //办卡收益
    public static final int INCOME_BK = 3;
    //贷款收益
    public static final int INCOME_DK = 4;
    //积分兑换收益
    public static final int INCOME_JF = 5;
    //卡测评收益
    public static final int INCOME_CP = 6;
    //征信查询收益
    public static final int INCOME_ZX = 7;
    //默认  升级/还款/快捷/信用卡/贷款/积分/备用1/备用2/备用3/备用4
    public static final String INCOME_DEFAULT = "0/0/0/0/0/0/0/0/0/0";
    
    public static String contributeMoney(String source,BigDecimal money,int indexType) {
		String[] split;
		try {
			split = source.split("/");
			split[indexType] = new BigDecimal(split[indexType]).add(money).toString();
		}catch (Exception e) {
			split = INCOME_DEFAULT.split("/");
			split[indexType] = money.add(new BigDecimal(split[indexType])).toString();
		}
		source = org.apache.commons.lang3.StringUtils.join(split, "/");
		return source;
	}
    
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    public static String getRealAddressByIP(String ip)
    {
        String address = "XX XX";

        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return "内网IP";
        }
        if (Global.isAddressEnabled())
        {
            String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
            if (StringUtils.isEmpty(rspStr))
            {
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            JSONObject obj;
            try
            {
                obj = JSON.unmarshal(rspStr, JSONObject.class);
                JSONObject data = obj.getObj("data");
                String region = data.getStr("region");
                String city = data.getStr("city");
                address = region + " " + city;
            }
            catch (Exception e)
            {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return address;
    }
}
